package com.example.hs.Service;

import com.example.hs.Pojo.User;
import com.example.hs.Repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User register(User user) {
        if (userRepository.existsBynum(user.getNum())) {
           return null;
        }
        return userRepository.save(user);
    }

    public User login(Long num, String password, HttpSession session) {
        User user = userRepository.findByNumAndPassword(num, password);
        if (user != null) {
            session.setAttribute("user", user); // 将用户信息存入Session
            return user;
        } else {
            throw new RuntimeException("Invalid credentials");
        }
    }

    public void logout(HttpSession session) {
        session.invalidate(); // 使Session失效
    }

    public User updateProfile(int userId, User updatedUser) {
       User user = userRepository.findById(userId).orElse(null);
       if (user != null) {
           user.setUsername(updatedUser.getUsername());
           user.setNum(updatedUser.getNum());
           user.setAvatarUrl(updatedUser.getAvatarUrl());
           return userRepository.save(user);
       } else {
           return null;
       }
    }

    public User getProfile(Integer userId) {
        return userRepository.findById(userId).orElse(null);
    }
}
